/*
 * Copyright (c) 2009, Jan Pastor. All Rights Reserved.
 */

package sk.jp.jitag.ui.common;

import javax.swing.ImageIcon;

import sk.jp.commons.exception.ApplicationException;
import sk.jp.commons.tools.ResourceLoader;
import sk.jp.commons.utils.ExceptionUtils;
import sk.jp.commons.objcache.ObjectCache;

/**
 * Helper class for loading image icons.
 * <p>With cache.
 */
public class IconLoader {

    private static ObjectCache<ImageIcon> imageIconCache = new ObjectCache<ImageIcon>(1000*60*15);

    private IconLoader() {
    }

    //----------------------------------------------------------------------

    /**
     * Loads an icon image.
     * @param icon icon to load.
     * @return icon image.
     */
    public static synchronized ImageIcon loadIcon(Icons icon){
        ImageIcon imageIcon = imageIconCache.getItem(icon.name());
        if(imageIcon == null){
            imageIcon = new ImageIcon(loadBytes(icon));
            imageIconCache.putItem(icon.name(), imageIcon);
        }
        return imageIcon;
    }

    /**
     * Loads a content of icon file.
     * @param icon
     * @return content.
     */
    private static byte[] loadBytes(Icons icon){
        try {
            return ResourceLoader.loadBinaryResource(IconLoader.class.getClassLoader(),
                                                     icon.getPath());
        } catch (Exception e) {
            throw new ApplicationException("Can't load icon image", null,
                               ExceptionUtils.paramsToMap("icon", icon.getFileName()),
                               e);
        }
    }

}
